<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { computed, ref, unref } from 'vue';
  import { shopInfoInfo, shopInfoAdd, shopInfoUpdate, shopInfoList } from '@/api/shop/manage';
  import { modalSchemas } from './manage.data';
  import { listToTree } from '@/utils/helper/treeHelper';

  defineOptions({ name: 'ShopInfoModal' });

  const emit = defineEmits(['register', 'reload']);

  const isUpdate = ref<boolean>(false);
  const title = computed<string>(() => {
    return isUpdate.value ? '编辑店铺信息' : '新增店铺信息';
  });

  const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
    async (data: { record?: Recordable; update: boolean }) => {
      modalLoading(true);
      const { record, update } = data;
      isUpdate.value = update;
      if (update && record) {
        const ret = await shopInfoInfo(record.id);
        await setFieldsValue(ret);
      }
      // 下拉框初始化
      await initShopInfoSelect();
      modalLoading(false);
    },
  );

  async function initShopInfoSelect() {
    // 需要动态更新TreeSelect组件 这里允许为空
    const listData = await shopInfoList();
    const treeData = listToTree(listData, { id: 'shopId', pid: 'parentShopId' });
    await updateSchema({
      field: 'parentShopId',
      componentProps: {
        treeData,
        treeLine: { showLeafIcon: false },
        fieldNames: { label: 'shopInfoName', value: 'shopInfoId' },
        treeDefaultExpandAll: true,
      },
    });
  }

  const [registerForm, { setFieldsValue, resetForm, validate, updateSchema }] = useForm({
    labelWidth: 100,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
    schemas: modalSchemas,
  });

  async function handleSubmit() {
    try {
      modalLoading(true);
      const data = await validate();
      if (unref(isUpdate)) {
        await shopInfoUpdate(data);
      } else {
        await shopInfoAdd(data);
      }
      await resetForm();
      emit('reload', closeModal);
    } catch (e) {
    } finally {
      modalLoading(false);
    }
  }
</script>

<style scoped></style>
